
from django.shortcuts import render,redirect
from app01.utils.pagination import Pagination
from app01.utils.form import *

def depart_list(request):
    """部门列表"""
    # 获取Department表的数据 [对象,对象]
    queryset = models.Department.objects.all().order_by('id')
    page_object = Pagination(request,queryset,page_size=2)
    context = {
        "queryset":page_object.page_queryset,
        "page_string":page_object.html()
    }

    return render(request,'depart_list.html',context)

def depart_add(request):
    """新增部门"""
    if request.method == "GET":
        return render(request, 'depart_add.html')
    # 获取用户提交的数据
    title = request.POST.get('title')
    print('title: ',title)
    # 保存到数据库
    models.Department.objects.create(title=title)

    # 重定向的列表页面
    return redirect('/depart/list')

def depart_delete(request):
    """删除部门"""
    nid = request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect('/depart/list')

def depart_edit(request,nid):
    print('nid:', nid)
    if request.method == 'GET':
        # 根据nid，获取数据
        row_object = models.Department.objects.filter(id=nid).first()

        return render(request,'depart_edit.html',{'row_object':row_object})
    newTitle = request.POST.get('new_title')
    models.Department.objects.filter(id=nid).update(title=newTitle)
    return redirect('/depart/list')

